import 'package:carousel_slider/carousel_slider.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:wallpaper/api/mobile.dart';
import 'package:wallpaper/api/mohu.dart';
import 'package:wallpaper/components/avatar.dart';
import 'package:wallpaper/components/images/image_load.dart';
import 'package:wallpaper/components/images/image_view.dart';
import 'package:wallpaper/components/list_title/my_list_title.dart';
import 'package:wallpaper/components/list_title/my_list_title_model.dart';
import 'package:wallpaper/model/image_base.dart';
import 'package:wallpaper/model/options_base.dart';
import 'package:wallpaper/pages/navbar/child/mobile_home.dart';
import 'package:wallpaper/pages/other/love_page.dart';
import 'package:wallpaper/pages/other/search_image.dart';
import 'package:wallpaper/tools/route_animation.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with TickerProviderStateMixin {
  List<ImageBase> images = [];
  List<ImageBase> newImages = [];
  List<ImageBase> hotImages = [];
  List<MyListTitleModel> list1 = [];
  List<MyListTitleModel> list2 = [];
  void getWallpaper() async {
    if (!mounted) return;
    Response res = await mohuImgsApi(id: 'img1', num: 5);
    if (res.data['code'] == '200') {
      setState(() {
        for (var item in res.data['pic']) {
          ImageBase image = ImageBase(
            smallPath: item,
            largePath: item.toString().replaceAll('mw690', 'large'),
            tags: '',
          );
          images.add(image);
        }
      });
    }
  }

  void getNewWallpaper() async {
    if (!mounted) return;
    Response res = await mobileAll(page: 1, limit: 10, order: 'new');
    if (res.data['msg'] == 'success') {
      setState(() {
        for (var item in res.data['res']['vertical']) {
          ImageBase image = ImageBase(
            smallPath: item['thumb'],
            largePath: item['img'],
            tags: '',
          );
          newImages.add(image);
        }
      });
    }
  }

  void getHotWallpaper() async {
    if (!mounted) return;
    Response res = await mobileAll(page: 1, limit: 10, order: 'hot');
    if (res.data['msg'] == 'success') {
      setState(() {
        for (var item in res.data['res']['vertical']) {
          ImageBase image = ImageBase(
            smallPath: item['thumb'],
            largePath: item['preview'],
            tags: '',
          );
          hotImages.add(image);
        }
      });
    }
  }

  void goImageView(List<ImageBase> images, int index, bool isMobile) {
    Navigator.push(
      context,
      MaterialPageRoute(
          builder: (context) => ImageView(
                images: images,
                selectedIndex: index,
                resetGetdata: () {},
                isMobile: isMobile,
              )),
    );
  }

  @override
  void initState() {
    getWallpaper();
    getNewWallpaper();
    getHotWallpaper();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    list1 = [
      MyListTitleModel(
        title: '最新壁纸',
        leading: Icon(Icons.spa_outlined,
            color: Theme.of(context).colorScheme.primary),
        route: MobileHome(
          title: '最新壁纸',
          order: 'new',
        ),
      )
    ];
    list2 = [
      MyListTitleModel(
        title: '热门壁纸',
        leading: Icon(Icons.whatshot_outlined, color: Colors.deepOrange),
        route: MobileHome(
          title: '热门壁纸',
          order: 'hot',
        ),
      )
    ];
    return Scaffold(
        appBar: AppBar(
          toolbarHeight: 40,
          elevation: 0,
          backgroundColor: Theme.of(context).colorScheme.primaryContainer,
          surfaceTintColor: Theme.of(context).colorScheme.primaryContainer,
          title: _buildHeader(context),
        ),
        body: RefreshIndicator(
          onRefresh: () {
            setState(() {
              images.clear();
              newImages.clear();
              hotImages.clear();
            });
            getWallpaper();
            getNewWallpaper();
            getHotWallpaper();
            return Future.delayed(
                Duration(milliseconds: OptionsBase().refreshTime));
          },
          child: Padding(
            padding: const EdgeInsets.all(5),
            child: ListView(
              children: [
                SizedBox(height: 10),
                _buildCarousel(),
                _buildNewWallpaper(list1, newImages),
                _buildNewWallpaper(list2, hotImages),
                SizedBox(height: 10),
              ],
            ),
          ),
        ));
  }

  Widget _buildHeader(BuildContext context) => Container(
        color: Theme.of(context).colorScheme.primaryContainer,
        child: Row(children: [
          Avatar(),
          Expanded(
            child: InkWell(
              onTap: () {
                Navigator.push(context,
                    MaterialPageRoute(builder: (context) => SearchImage()));
              },
              child: Container(
                margin: const EdgeInsets.only(left: 10, right: 10),
                height: 28,
                decoration: BoxDecoration(
                    color: Theme.of(context).colorScheme.surface,
                    borderRadius: const BorderRadius.all(Radius.circular(15))),
                child: Flex(direction: Axis.horizontal, children: [
                  const SizedBox(width: 10),
                  const Icon(Icons.search, color: Colors.grey),
                  Text('搜点什么···',
                      style: TextStyle(fontSize: 14, color: Colors.grey)),
                ]),
              ),
            ),
          ),
          InkWell(
            onTap: () {
              RouteAnimation().animateRoute(context, LovePage());
            },
            child: Icon(
              Icons.collections_sharp,
              color: Theme.of(context).colorScheme.onSurface,
              size: 26,
            ),
          ),
        ]),
      );

  Widget _buildCarousel() {
    return CarouselSlider(
      options: CarouselOptions(
        height: 160,
        enlargeCenterPage: true,
        autoPlay: true,
        autoPlayAnimationDuration: Duration(milliseconds: 1000),
      ),
      items: images.map((i) {
        return Builder(
          builder: (BuildContext context) {
            return GestureDetector(
              onTap: () {
                goImageView(images, images.indexOf(i), false);
              },
              child: ClipRRect(
                borderRadius: BorderRadius.circular(10),
                child: Container(
                  width: MediaQuery.of(context).size.width,
                  margin: EdgeInsets.symmetric(horizontal: 5.0),
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(10),
                      boxShadow: [
                        BoxShadow(
                          color: Theme.of(context).colorScheme.shadow,
                          offset: Offset(1, 2),
                          blurRadius: 2,
                        ),
                      ]),
                  child: ImageLoad(imageUrl: i.smallPath),
                ),
              ),
            );
          },
        );
      }).toList(),
    );
  }

  Widget _buildNewWallpaper(
      List<MyListTitleModel> list, List<ImageBase> images) {
    return Container(
      height: 280,
      margin: const EdgeInsets.only(top: 10),
      decoration: BoxDecoration(
        color: Theme.of(context).colorScheme.primaryContainer,
        borderRadius: BorderRadius.circular(10),
      ),
      child: Column(
        children: [
          MyListTitle(
            list: list,
            height: 25,
          ),
          SizedBox(height: 5),
          Expanded(
            child: Padding(
              padding: const EdgeInsets.only(left: 5, right: 5, bottom: 5),
              child: ListView.builder(
                  scrollDirection: Axis.horizontal,
                  itemCount: images.length,
                  itemBuilder: (context, index) {
                    return Padding(
                      padding: const EdgeInsets.all(5),
                      child: GestureDetector(
                        onTap: () {
                          goImageView(images, index, true);
                        },
                        child: ClipRRect(
                          borderRadius: BorderRadius.circular(10),
                          child: Container(
                            width: 150,
                            decoration: BoxDecoration(
                                color: Theme.of(context).colorScheme.secondary,
                                borderRadius: BorderRadius.circular(10),
                                boxShadow: [
                                  BoxShadow(
                                    color: Theme.of(context).colorScheme.shadow,
                                    offset: Offset(1, 2),
                                    blurRadius: 2,
                                  ),
                                ]),
                            child: ImageLoad(imageUrl: images[index].smallPath),
                          ),
                        ),
                      ),
                    );
                  }),
            ),
          ),
        ],
      ),
    );
  }
}
